`
<template>
  <div>
    <a-upload
        v-model:file-list="fileList"
        name="file"
        action="http://localhost:9191/user/uploadAva"
        :before-upload="beforeUpload"
        :show-upload-list="false"
        @change="handleChange">
       <a-button>
        <upload-outlined></upload-outlined>
        Click to Upload
      </a-button>
    </a-upload>
  </div>
</template>

<script>
import {UploadOutlined} from '@ant-design/icons-vue';
import {message} from 'ant-design-vue';
import {defineComponent, ref} from 'vue';

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default {
  emits: ["sendMsg"],
  name: "uploadCPM",
  components: {
    UploadOutlined,
  },
  data() {
    return {}
  }
  ,
  setup(props, context) {

    const fileList = ref([]);
    const loading = ref(false);
    const imageUrl = ref('');

    const handleChange = info => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        if (info.file.response.code === 0) {
          context.emit('sendMsg', info.file.response.fileUrl)
          // Get this url from response in real world.
          getBase64(info.file.originFileObj, base64Url => {
            imageUrl.value = base64Url;
            loading.value = false;
          });
        }
      }

      if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
      }
    };

    const beforeUpload = file => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

      if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
      }

      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
      }

      return isJpgOrPng && isLt2M;
    };

    return {
      fileList,
      loading,
      imageUrl,
      handleChange,
      beforeUpload,
    };
  }
  ,
}
</script>

<style scoped>
/deep/ .ant-upload{
  width: 170px;
}
</style>
`
